#pragma once
#include "../common/message.hpp"
#include "../common/net.hpp"
#include <set>

namespace RPC
{
    namespace server
    {
        class ProviderManager
        {
        public:
            using ptr = std::shared_ptr<ProviderManager>;
            struct Provider
            {
                std::mutex _mutex;
                using ptr = std::shared_ptr<Provider>;
                BaseConnection::ptr conn;
                Address host;
                std::vector<std::string> methods;
                Provider(const BaseConnection::ptr &c, const Address &h)
                    : conn(c), host(h)
                {
                }
                void appendMethod(const std::string &method)
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    methods.emplace_back(method);
                }
            };

            // 新的服务提供者进行服务注册的时候调用;
            void addProvider(const BaseConnection::ptr &c, const Address &h, const std::string &method)
            {
                Provider::ptr provider;
                // 查找一个所关联的服务提供者; 找到就获取, 找不到创建, 建立关联;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _conns.find(c);
                    if (it != _conns.end())
                    {
                        provider = it->second;
                    }
                    else
                    {
                        provider = std::make_shared<Provider>(c, h);
                        _conns.insert(std::make_pair(c, provider));
                    }
                    // mthod方法的提供主机要新增数据;
                    auto& providers = _providers[method];
                    providers.insert(provider);
                    // 向服务对象中新增一个提供的服务名称;
                }
            }
            // 服务提供者断开的时候, 获取信息进行服务下线通知.
            Provider::ptr getProvider(const BaseConnection::ptr &c)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _conns.find(c);
                if (it != _conns.end())
                {
                    return it->second;
                }
                return Provider::ptr();
            }
            // 服务提供者断开的时候, 删除关联信息.
            void delProvider(const BaseConnection::ptr& c)
            { 
                std::unique_lock<std::mutex> lock(_mutex);
                // 查找一个所关联的服务提供者; 找到就获取, 找不到创建, 建立关联;
                {
                    auto it = _conns.find(c);
                    if (it == _conns.end())
                    {
                        //当前断开的不是服务提供者;
                        return;
                    }

                    //是提供者看提供了什么服务, 从中删除当前提供者.
                    for(auto& method : it->second->methods)
                    {
                        auto& providers = _providers[method];
                        providers.erase(it->second);
                    }
                    _conns.erase(it);
                }
            }
            std::vector<Address> methodHosts(const std::string& method)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _providers.find(method);
                if(it == _providers.end())
                {
                    return std::vector<Address>();
                }
                std::vector<Address> result(it->second.begin(), it->second.end());
                return result;
            }
        private:
            std::mutex _mutex;
            std::unordered_map<std::string, std::set<Provider::ptr>> _providers;
            std::unordered_map<BaseConnection::ptr, Provider::ptr> _conns;
        };

        class DiscoverManager
        {
        public:
            using ptr = std::shared_ptr<DiscoverManager>;
            struct Discoverer
            {
                using ptr = std::shared_ptr<Discoverer>;
                std::mutex _mutex;
                // 客户端连接;
                BaseConnection::ptr conn;
                // 发现过的服务名称;
                std::vector<std::string> methods;
                Discoverer(const BaseConnection::ptr &c)
                    :conn(c)
                {}

                void appendMethod(const std::string &method)
                {
                    std::unique_lock<std::mutex> loc(_mutex);
                    methods.push_back(method);
                }
            };

            // 每次客户端进行发现服务时候新增发现者, 新增服务名称.
            Discoverer::ptr addDiscoverer(const BaseConnection::ptr &c, const std::string& method)
            {
                Discoverer::ptr discoverer;
                {
                    std::unique_lock<std::mutex> loc(_mutex);
                    auto it = _conns.find(c);
                    if(it != _conns.end())
                    {
                        discoverer = it->second;
                    }
                    else
                    {
                        discoverer = std::make_shared<Discoverer>(c);
                        _conns.insert(std::make_pair(c, discoverer));
                    }
                    auto& discoverers = _discoverers[method];
                    discoverers.insert(discoverer);
                }
                discoverer->appendMethod(method);
                return discoverer;
            }

            // 发现者客户端断开连接, 找到发现者信息, 删除关联信息.
            void delDiscoverer(const BaseConnection::ptr &c)
            {
                std::unique_lock<std::mutex> loc(_mutex);
                auto it = _conns.find(c);
                if(it == _conns.end())
                {
                    //没有找到对应发现者信息, 不是服务发现者;
                    return;
                }

                for(auto& method : it->second->methods)
                {
                    auto discoverers = _discoverers[method];
                    discoverers.erase(it->second);
                }
                _conns.erase(it);
            }

            // 当有一个新的提供者上/下线, 进行上/下线通知.
            void onlineNotify(const std::string &method, const Address& host)
            {
                return notify(method, host, ServiceOpType::SERVICE_ONLINE);
            }
            
            void offlineNotify(const std::string &method, const Address& host)
            {
                return notify(method, host, ServiceOpType::SERVICE_OFFLINE);
            }
        private:
            void notify(const std::string& method, const Address& host, ServiceOpType optype)
            {
                std::unique_lock<std::mutex> loc(_mutex);
                auto it = _discoverers.find(method);
                if(it == _discoverers.end())
                {
                    //这个服务没有发现者;
                    return;
                }

                auto msg_req = MessageFactory::create<ServiceRequest>();
                RPC::UUID u;
                msg_req->setId(u.uuid());
                msg_req->setMType(MType::REQ_SERVICE);
                msg_req->setMethod(method);
                msg_req->setHost(host);
                msg_req->setOptype(optype);
                for(auto& discoverer : it->second)
                {
                    discoverer->conn->send(msg_req);
                }
            }
        private:
            std::mutex _mutex;
            std::unordered_map<std::string, std::set<Discoverer::ptr>> _discoverers;
            std::unordered_map<BaseConnection::ptr, Discoverer::ptr> _conns;
        };

        class PDManager
        {
        public:
            using ptr = std::shared_ptr<PDManager>;
            PDManager()
                :_providers(std::make_shared<ProviderManager>())
                ,_discoverers(std::make_shared<DiscoverManager>())
            {}

            void onServiceRequest(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg)
            {
                //服务操作请求, 服务注册, 服务发现;
                ServiceOpType optype  = msg->Optype();
                if(optype == ServiceOpType::SERVICE_REGISTRY)
                {
                    //服务注册;
                    //1新增服务提供者;//2.进行服务上线的通知;
                    _providers->addProvider(conn, msg->host(), msg->method());
                    _discoverers->onlineNotify(msg->method(), msg->host());
                    return registryResponse(conn, msg);
                }
                else if(optype == ServiceOpType::SERVICE_DISCOVERY)
                {
                    //服务发现: 新增服务发现;
                    _discoverers->addDiscoverer(conn, msg->method());
                    return discoverResponse(conn, msg);
                }
                else
                {
                    ELOG("收到服务操作, 但是操作类型错误!");
                    return errorResponse(conn, msg);
                }
                
                
            }
            void onConnShutdown(const BaseConnection::ptr &conn)
            {
                auto provider = _providers->getProvider(conn);
                if(provider.get() != nullptr)
                {
                    for(auto& method : provider->methods)
                    {
                        _discoverers->offlineNotify(method, provider->host);
                    }
                    _providers->delProvider(conn);
                }
                _discoverers->delDiscoverer(conn);
            }
        private:
            void errorResponse(const BaseConnection::ptr& conn, const ServiceRequest::ptr& msg)
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                msg_rsp->setId(msg->rid());
                msg_rsp->setMType(MType::RSP_SERVICE);
                msg_rsp->setRCode(RCode::RCODE_INVALID_OPTYPE);
                msg_rsp->setOptype(ServiceOpType::SERVICE_UNKNOW);
                conn->send(msg_rsp);
            }

            void registryResponse(const BaseConnection::ptr& conn, const ServiceRequest::ptr& msg)
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                msg_rsp->setId(msg->rid());
                msg_rsp->setMType(MType::RSP_SERVICE);
                msg_rsp->setRCode(RCode::RCODE_OK);
                msg_rsp->setOptype(ServiceOpType::SERVICE_REGISTRY);
                conn->send(msg_rsp);
            }

            void discoverResponse(const BaseConnection::ptr& conn, const ServiceRequest::ptr& msg)
            {
                auto msg_rsp = MessageFactory::create<ServiceResponse>();
                std::vector<Address> hosts = _providers->methodHosts(msg->method());
                msg_rsp->setId(msg->rid());
                msg_rsp->setMType(MType::RSP_SERVICE);
                msg_rsp->setOptype(ServiceOpType::SERVICE_DISCOVERY);
                if(hosts.empty())
                {
                    msg_rsp->setRCode(RCode::RCODE_NOT_FOUND_SERVICE);
                    return conn->send(msg_rsp);
                }
                msg_rsp->setRCode(RCode::RCODE_OK);
                msg_rsp->setMethod(msg->method());
                msg_rsp->setHost(hosts);
                return conn->send(msg_rsp);
            }
        private:
            ProviderManager::ptr _providers;
            DiscoverManager::ptr _discoverers;
        };
    }
}